JavaScript Unlocked by Dmitry Sheiko

JavaScript Unlocked by Dmitry Sheiko

Author:Dmitry Sheiko [Sheiko, Dmitry]
Language: eng
Format: epub, azw3, pdf
Publisher: Packt Publishing
Published: 2015-12-06T23:00:00+00:00


Boosting performance with JavaScript workers

JavaScript is a single-threaded environment. So, multiple scripts cannot really run simultaneously. Yes, we use setTimeout(), setInterval(), XMLHttpRequest and event handlers to run tasks asynchronously. So we gain non-blocking execution, but this doesn't mean concurrency. However, using web workers, we can run one or more scripts in the background independent of the UI scripts. Web workers are long running scripts that are not interrupted by blocking UI events. Web workers utilize multithreading, so we can benefit from multicore CPUs.

Well, where can we use web workers? Anywhere where we do processor-intensive calculations and don't want them blocking the UI thread. It can be graphics, web games, crypto, and Web I/O. We cannot manipulate the DOM from a web worker directly, but we have access to XMLHttpRequest, Web Storage, IndexedDB, FileSystem API, Web Sockets and other features.

So let's see what these web workers are in practice. By and large, we register an existing web worker in the main script and communicate to the web worker using the PostMessage API (https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage):

index.html <html> <body> <script> "use strict"; // Register worker var worker = new Worker( "./foo-worker.js" ); // Subscribe for worker messages worker.addEventListener( "message", function( e ) { console.log( "Result: ", e.data ); }, false ); console.log( "Starting the task..." ); // Send a message to worker worker.postMessage({ command: "loadCpu", value: 2000 }); </script> </body> </html> foo-worker.js "use strict"; var commands = { /** * Emulate resource-consuming operation * @param {Number} delay in ms */ loadCpu: function( delay ) { var start = Date.now(); while (( Date.now() - start ) < delay ); return "done"; } }; // Workers don't have access to the window object. // To access global object we have to use self object instead. self.addEventListener( "message", function( e ) { var command; if ( commands.hasOwnProperty( e.data.command ) ) { command = commands[ e.data.command ]; return self.postMessage( command( e.data.value ) ); } self.postMessage( "Error: Command not found" ); }, false );



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.